package ru.myrtle.umf.query;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import ru.myrtle.umf.UObject;

public class USelect {

    private final UFrom from;
    private final UWhere where;

    public USelect(UFrom from, UWhere where) {
        this.from = from;
        this.where = where;
    }

    public Collection<UObject> select() {
        Collection<UObject> selected = new ArrayList<UObject>();

        for (UObject object : from.getObjects()) {
            if (where.isSatisfied(object)) {
                selected.add(object);
            }
        }

        return selected;
    }

    public UObject selectSingleResult() {
        Iterator<UObject> it = select().iterator();

        if (!it.hasNext()) {
            throw new IllegalStateException(
                    "No objects found"
            );
        }
        else {
            UObject found = it.next();

            if (it.hasNext()) {
                throw new IllegalStateException(
                        "Too many objects found"
                );
            }

            return found;
        }
    }
}
